//
//  SelectFriendController.swift
//  选择好友
//
//  Created by smile on 2019/7/1.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//发布订阅框架
import SwiftEventBus

class SelectFriendController: BaseTitleController {
    
    
    /// 列表控件
    @IBOutlet weak var tableView: UITableView!
    
    /// 搜索控制器
    var searchController:UISearchController!
    
    
    /// 用户列表
    var dataArray:[UserGroup] = []
    
    /// 用户组标题
    var letterDataArray:[String] = []
    
    /// 用户搜索结果列表
    var resultDataArray:[UserGroup] = []
    
    /// 用户搜索结果组标题
    var resultLetterDataArray:[String] = []
    
    
    override func initViews() {
        super.initViews()
        
        setTitle("选择好友")
        
        //初始化搜索控制器
        searchController = UISearchController(searchResultsController: nil)
        
        //设置搜索控制器代理
        searchController.delegate = self
        
        //设置内容更新代理
        searchController.searchResultsUpdater = self
        
        //搜索时背景颜色变暗
        searchController.dimsBackgroundDuringPresentation=false
        
        //搜索时背景变模糊
        searchController.obscuresBackgroundDuringPresentation = false
        
        //进入手势状态后隐藏导航栏
        searchController.hidesNavigationBarDuringPresentation=false
        
        //添加searchBar到headerView
        tableView.tableHeaderView=searchController.searchBar
        
        //设置TableView右侧索引标题的颜色
        tableView.sectionIndexColor=UIColor(hex: COLOR_PRIMARY)
        
        //设置TableView右侧索引背景颜色
//        tableView.sectionIndexBackgroundColor=UIColor.lightGray
        
        //注册cell
        tableView.register(UINib(nibName: UserCell.NAME, bundle: nil), forCellReuseIdentifier: UserCell.NAME)
    }

    override func initDatas() {
        super.initDatas()
        
        Api
            .shared
            .friends(PreferenceUtil.userId()!).subscribeOnSuccess { (data) in
            if let data = data?.data {
                //测试对用户数据分组
                let groups = DataUtil.processUser(self.getTestData())

                //将处理后的数据添加到列表中
                self.dataArray = self.dataArray+groups
                
                //处理组标题
                self.letterDataArray = self.letterDataArray + DataUtil.processUserLetter(self.dataArray)
                
                print("SelectFriendController initDatas")
//                self.dataArray=self.dataArray+DataUtil.processUser(data)
                self.tableView.reloadData()

            }
        }.disposed(by: disposeBag)
    }

    /// 返回测试数据
    ///
    /// - Returns: <#return value description#>
    func getTestData() -> [User] {
        //创建一个列表
        var results:[User] = []
        
        for i in 0..<50 {
            let user = User()
            user.nickname = "我的云音乐\(i)"
            results.append(user)
        }
        
        for i in 0..<50 {
            let user = User()
            user.nickname = "爱学啊smile\(i)"
            results.append(user)
        }
        
        for i in 0..<50 {
            let user = User()
            user.nickname = "爱学啊李薇\(i)"
            results.append(user)
        }
        
        return results
    }
   
}

// MARK: - 启动方法
extension SelectFriendController {
    
    /// 启动方法
    ///
    /// - Parameter nav: <#nav description#>
    static func start(_ nav:UINavigationController) {
        //创建控制器
        let controller = nav.storyboard!.instantiateViewController(withIdentifier: "SelectFriend")
        
        //将控制放到导航控制器
        nav.pushViewController(controller, animated: true)
    }
}

// MARK: - 列表数据源和代理
extension SelectFriendController :UITableViewDataSource,UITableViewDelegate {
    
    /// 有多少组
    ///
    /// - Parameter tableView: <#tableView description#>
    /// - Returns: <#return value description#>
    func numberOfSections(in tableView: UITableView) -> Int {
        if searchController.isActive {
            return resultDataArray.count
        } else {
            return dataArray.count
        }
        
    }
    
    /// 有多少个
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return getGroup(section).datas.count
    }
    
    func getGroup(_ section:Int) -> UserGroup {
        if searchController.isActive {
            return resultDataArray[section]
        } else {
            return dataArray[section]
        }
        
    }
    
    /// 返回当前位置cell
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //获取cell
        let cell = tableView.dequeueReusableCell(withIdentifier: UserCell.NAME, for: indexPath) as! UserCell
        
        //取出组
        let group = getGroup(indexPath.section)
        
        //绑定数据
        cell.bindData(group.datas[indexPath.row])
        
        //返回cell
        return cell
    }
    
    /// 点击回调方法
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //发送选择数据
        SwiftEventBus.post(ON_SELECT_USER, sender: getGroup(indexPath.section).datas[indexPath.row])
        
        //关闭当前界面
        navigationController!.popViewController(animated: true)
    }
    
    /// 返回组标题
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return getGroup(section).title
    }
    
    /// 返回TableView右侧索引的标题
    ///
    /// - Parameter tableView: <#tableView description#>
    /// - Returns: <#return value description#>
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        if searchController.isActive {
            return resultLetterDataArray
        } else {
            return letterDataArray
        }
        
    }
    
    /// 返回section（分组）与右侧字母索引的对应关系
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - title: <#title description#>
    ///   - index: <#index description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return index
    }
}

// MARK: - 搜索状态
//都是可选的协议
//只有需要的时候才重写
extension SelectFriendController:UISearchControllerDelegate{
    
    /// 即将进入搜索状态
    ///
    /// - Parameter searchController: <#searchController description#>
    func willPresentSearchController(_ searchController: UISearchController) {
       print("SelectFriendController willPresentSearchController")
    }
    
    /// 已经进入了搜索状态
    ///
    /// - Parameter searchController: <#searchController description#>
    func didPresentSearchController(_ searchController: UISearchController) {
        print("SelectFriendController didPresentSearchController")
    }
    
    /// 即将退出搜索状态
    ///
    /// - Parameter searchController: <#searchController description#>
    func willDismissSearchController(_ searchController: UISearchController) {
        print("SelectFrindController willDismissSearchControler")
    }
    
    /// 已经退出了搜索状态
    ///
    /// - Parameter searchController: <#searchController description#>
    func didDismissSearchController(_ searchController: UISearchController) {
        print("SelectFriendController didDismissSearchController")
    }
    
    /// 点赞了搜索输入框
    ///
    /// - Parameter searchController: <#searchController description#>
    func presentSearchController(_ searchController: UISearchController) {
        print("SelectFriendController presentSearchController")
    }
}

// MARK: - 搜索输入框协议
extension SelectFriendController:UISearchResultsUpdating {
    
    /// 搜索输入框内容改变了
    ///
    /// - Parameter searchController: <#searchController description#>
    func updateSearchResults(for searchController: UISearchController) {
        
        //去掉前后的空格
        let searchString=searchController.searchBar.text?.trim()
        
        //移除原来的数据
//        resultDataArray.removeAll()
//        resultLetterDataArray.removeAll()
        
        //过滤用户数据
        resultDataArray = DataUtil.filterUser(dataArray, searchString!)
        
        //获取搜索结果的标题
        resultLetterDataArray = DataUtil.processUserLetter(resultDataArray)
        
        tableView.reloadData()
        
        print("SelectFriendController updateSearchResults:\(searchString)")
    }
}
